#include "mainwindow.h"
#include "ui_mainwindow.h"

const unsigned int scrollSpeed = 3;
const unsigned int _scrollSleep = 5;
const unsigned int showDelay = 3000;

void MainWindow::msleep(unsigned long msecs)
{
    QTime dieTime = QTime::currentTime().addMSecs(msecs);
    while( QTime::currentTime() < dieTime && !stopSleep)
    {
            QCoreApplication::processEvents(QEventLoop::AllEvents, msecs);
    }
}

void MainWindow::showNotifier()
{
    qDebug(" * Showing notifier");
    int availableWidth = QApplication::desktop()->availableGeometry().width();
    int availableHeight = QApplication::desktop()->availableGeometry().height();
    int availableLeft = QApplication::desktop()->availableGeometry().left();
    int availableTop = QApplication::desktop()->availableGeometry().top();
    int fullHeight = QApplication::desktop()->screenGeometry().height();
    int scrollSleep = _scrollSleep;
    for (int top = fullHeight; (top > availableTop + availableHeight - this->height() - 1 && running); top-=scrollSpeed, scrollSleep += (fullHeight - top) / 80)
    {
        this->move(availableLeft + availableWidth - this->width(), top);
        this->show();
        msleep(scrollSleep);
    }
    if (!running)
        return;
    qDebug(" * Waiting...");
    msleep(showDelay);
    qDebug(" * Hiding notifier");
    for (int top = availableTop + availableHeight - this->height(); (top <= fullHeight && running); top+=scrollSpeed, scrollSleep -= (fullHeight - top) / 80)
    {
        this->move(availableLeft + availableWidth - this->width(), top);
        this->show();
        msleep(scrollSleep);
    }
    this->hide();
}

void MainWindow::check(bool forceToolTip)
{
    if (notifierShowed)
        return;
    QString q = checker->getNewMessages(this->ui->infoLabel);
    qDebug(" * Unread count (or error): %s", q.toAscii().data());
    if (q != "0")
        ++renotifyCount;
    if (forceToolTip || q != lastQ || renotifyCount > 5)
    {
        renotifyCount = 0;
        bool isInt;
        q.toInt(&isInt, 10);
        if (q == "0")
        {
            setIcon(standartIcon);
            trayIcon->setToolTip(tr("You haven't unread messages."));
        }
        else if (isInt)
        {
            setIcon(standartIcon);
            trayIcon->setToolTip(tr("You have %1 unread message(s).").arg(q)); // TODO: plural translate
        }
        notifierShowed = true;
        showNotifier();
        notifierShowed = false;
    }
    lastQ = q;
}

void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::Trigger)
        check(true);
}

MainWindow::MainWindow(QString email, QString pass, QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindowClass)
{
    renotifyCount = 0;
    imageDir = "/usr/share/kcheckvkontakte/";
    this->setGeometry(QRect(10000, 10000, 200, 90));
    ui->setupUi(this);
    createActions();
    createTrayIcon();
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
    trayIcon->show();
    options = new Options();
    aboutWindow = new aboutDialog();
//    QPalette pal = QPalette();
//    ui->backgroundLabel->setBackgroundRole(pal.Base);
    //QImage image = QImage("vkontakte.jpg");
//    QPixmap pixmap = QPixmap();
//    pixmap.load(imageDir + "vkontakte.xpm");
//    ui->backgroundLabel->setPixmap(pixmap);
    ui->infoLabel->setText(tr("<font color='white'>Unread messages: 0</font>"));
    this->setWindowFlags(Qt::ToolTip);
    //Loading some info for optionsWindow
    options->load();
    if ((email != "") && (pass != ""))
    {
        options->email = email;
        options->password = pass;
    }
// First run
    running = false;
    mainTimer = new QTimer(this);
    mainTimer->singleShot(1000, this, SLOT(onTimer()));
}

MainWindow::~MainWindow()
{
    qDebug(" * Deleting objects...");
    // TODO: normal destructor
//    delete mainTimer;
//    mainTimer = NULL;
//    delete aboutWindow;
//    aboutWindow = NULL;
//    delete options;
//    options = NULL;
//    delete trayIconMenu;
//    trayIconMenu = NULL;
//    delete trayIcon;
//    trayIcon = NULL;
//    delete checker;
//    checker = NULL;
//    delete ui;
//    ui = NULL;
}

void MainWindow::quit()
{
    qDebug(" * Quitting...");
    running = false;
    stopSleep = true;
    mainTimer->stop();
    options->close();
    this->close();
    QCoreApplication::quit();
}

void MainWindow::createActions()
{
    optionsAction = new QAction(tr("&Options"), this);
    connect(optionsAction, SIGNAL(triggered()), this, SLOT(showOptions()));
    aboutAction = new QAction(tr("&About"), this);
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));

    quitAction = new QAction(tr("&Quit"), this);
    connect(quitAction, SIGNAL(triggered()), this, SLOT(quit()));
}

void MainWindow::showOptions()
{
    if (!options->optionsWindowActive)
    {
        qDebug(" * Showing options-dialog");
        options->showOptions(&running, &stopSleep);
    }
}

void MainWindow::showAbout()
{
    qDebug(" * Showing about-dialog");
    aboutWindow->showAbout();
//    if (!options->optionsWindowActive)
//        options->showOptions(&running, &stopSleep);
}

void MainWindow::setIcon(QString fileName)
{
    QIcon icon(fileName);
//    trayIcon->setIcon(icon);
//    setWindowIcon(icon);
//    QPixmap pixmap = ui->infoLabel->pixmap()->copy(ui->infoLabel->pixmap()->rect());
//    pixmap.fromImage(ui->infoLabel->pixmap()->toImage());
//    QIcon icon = QIcon(pixmap);
    trayIcon->setIcon(icon);
    setWindowIcon(icon);
}


void MainWindow::createTrayIcon()
{
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(optionsAction);
    trayIconMenu->addAction(aboutAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);

    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);
    standartIcon = ":/images/logo_vkontakte.png"; //imageDir + "logo_vkontakte.xpm";
    setIcon(standartIcon);
}

void MainWindow::onTimer()
{
    if ((options->email == "") || (options->password == ""))
    {
        showOptions();
        //Try again...
        mainTimer = new QTimer(this);
        mainTimer->singleShot(1000, this, SLOT(onTimer()));
    }
    else
    {
        if (!running)
        {
            // Creating & configuring main class
            checker = new VKChecker(options->email, options->password);
            checker->setProxyInfo(options->useProxy, options->proxyHost, options->proxyPort,
                                  options->useAuthorization, options->proxyUserName, options->proxyPassword);
            notifierShowed = false;
            lastQ = "last";            
            stopSleep = false;
            running = true;
        }
// Try to login & etc
        check(false);
// And recreate timer to next shot :)
        mainTimer = new QTimer(this);
        mainTimer->singleShot(options->timeout*1000, this, SLOT(onTimer()));
    }
}
